package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.List;

import com.ruoyi.system.domain.SysClasses;
import com.ruoyi.system.domain.SysCommonDataProperty;
import com.ruoyi.system.domain.SysDataType;
import com.ruoyi.system.protocol.IDynamicCacheService;
import com.ruoyi.system.protocol.IDynamicTableService;
import com.ruoyi.system.service.ISysClassesService;
import com.ruoyi.system.service.ISysCommonDataPropertyService;
import com.ruoyi.system.service.ISysDataTypeService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysDataProperty;
import com.ruoyi.system.service.ISysDataPropertyService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 基础字段Controller
 * 
 * @author ruoyi
 * @date 2021-10-31
 */
@RestController
@RequestMapping("/system/dataProperty")
public class SysDataPropertyController extends BaseController
{
    @Autowired
    private ISysDataPropertyService sysDataPropertyService;

    @Autowired
    private ISysCommonDataPropertyService sysCommonDataPropertyService;

    @Autowired
    private ISysClassesService sysClassesService;

    @Autowired
    private ISysDataTypeService sysDataTypeService;

    @Autowired
    private IDynamicTableService dynamicTableService;

    @Autowired
    private IDynamicCacheService dynamicCache;

    /**
     * 查询基础字段列表
     */
    @PreAuthorize("@ss.hasPermi('system:dataProperty:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysDataProperty sysDataProperty)
    {
        startPage();
        List<SysDataProperty> list = sysDataPropertyService.selectSysDataPropertyList(sysDataProperty);
        return getDataTable(list);
    }

    /**
     * 导出基础字段列表
     */
    @PreAuthorize("@ss.hasPermi('system:dataProperty:export')")
    @Log(title = "基础字段", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SysDataProperty sysDataProperty)
    {
        List<SysDataProperty> list = sysDataPropertyService.selectSysDataPropertyList(sysDataProperty);
        ExcelUtil<SysDataProperty> util = new ExcelUtil<SysDataProperty>(SysDataProperty.class);
        return util.exportExcel(list, "基础字段数据");
    }

    /**
     * 获取基础字段详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dataProperty:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(sysDataPropertyService.selectSysDataPropertyById(id));
    }

    /**
     * 新增基础字段
     */
    @PreAuthorize("@ss.hasPermi('system:dataProperty:add')")
    @Log(title = "基础字段", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysDataProperty sysDataProperty)
    {
        SysClasses sysClasses = sysClassesService.selectSysClassesById(sysDataProperty.getClassesId());
        SysDataType sysDataType = sysDataTypeService.selectSysDataTypeById(sysDataProperty.getDataTypeId());
        dynamicTableService.createColumn(sysClasses.getNameEn(), sysDataProperty.getNameEn(), sysDataProperty.getNameZh(), sysDataProperty.getFieldLength()+"", sysDataType.getFieldType());
        int i = sysDataPropertyService.insertSysDataProperty(sysDataProperty);
        dynamicCache.refreshDataPropertyListCache(sysClasses.getNameEn());
        dynamicCache.refreshFieldForwardAndReverse();
        return toAjax(i);
    }

    /**
     * 新增字段判重
     */
    @PreAuthorize("@ss.hasPermi('system:dataProperty:add')")
    @GetMapping("addRemovingRepeat/{nameEn}/{commonDataPropertyId}/{classesId}")
    public AjaxResult addRemovingRepeat(@PathVariable("nameEn") String nameEn, @PathVariable("commonDataPropertyId") Long commonDataPropertyId
            , @PathVariable("classesId") String classesId){
        List<SysDataProperty> sysDataPropertyList = sysDataPropertyService.selectSysDataPropertyList(null);
        if(commonDataPropertyId != null && commonDataPropertyId != 0){
            SysDataProperty sysDataProperty = sysDataPropertyList.stream()
                    .filter(x -> commonDataPropertyId.equals(x.getCommonDataPropertyId()) && nameEn.equals(x.getNameEn()) && classesId.equals(x.getClassesId()))
                    .findFirst().orElse(null);
            if(sysDataProperty != null){
                return success().put("msg","字段名不可用，已存在该公共字段");
            }
        }else{
            SysDataProperty sysDataProperty = sysDataPropertyList.stream()
                    .filter(x -> nameEn.equals(x.getNameEn()))
                    .findFirst().orElse(null);
            if(sysDataProperty != null){
                return success().put("msg", "字段名不可用，已存在该表字段");
            }
            List<SysCommonDataProperty> commonDataPropertyList = sysCommonDataPropertyService.selectSysCommonDataPropertyList(null);
            SysCommonDataProperty sysCommonDataProperty = commonDataPropertyList.stream().filter(x -> nameEn.equals(x.getNameEn())).findFirst().orElse(null);
            if(sysCommonDataProperty != null){
                return success().put("msg", "字段名不可用，与公共字段冲突");
            }
        }
        return success().put("msg", "success");
    }

    /**
     * 修改基础字段
     */
    @PreAuthorize("@ss.hasPermi('system:dataProperty:edit')")
    @Log(title = "基础字段", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysDataProperty sysDataProperty)
    {
        SysClasses sysClasses = sysClassesService.selectSysClassesById(sysDataProperty.getClassesId());
        int i = sysDataPropertyService.updateSysDataProperty(sysDataProperty);
        dynamicCache.refreshDataPropertyListCache(sysClasses.getNameEn());
        dynamicCache.refreshFieldForwardAndReverse();
        return toAjax(i);
    }

    /**
     * 删除基础字段
     */
    @PreAuthorize("@ss.hasPermi('system:dataProperty:remove')")
    @Log(title = "基础字段", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        List<String> classesEnList = new ArrayList<>();
        for (Long id : ids) {
            SysDataProperty sysDataProperty = sysDataPropertyService.selectSysDataPropertyById(id);
            SysClasses sysClasses = sysClassesService.selectSysClassesById(sysDataProperty.getClassesId());
            dynamicTableService.deleteColumn(sysClasses.getNameEn(), sysDataProperty.getNameEn());
            if(!classesEnList.contains(sysClasses.getNameEn())){
                classesEnList.add(sysClasses.getNameEn());
            }
        }
        for (String classesEn : classesEnList) {
            dynamicCache.refreshDataPropertyListCache(classesEn);
        }
        dynamicCache.refreshFieldForwardAndReverse();

        return toAjax(sysDataPropertyService.deleteSysDataPropertyByIds(ids));
    }
}
